package com.kstech.exccheck.view;


import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.widget.AdapterView.OnItemClickListener;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.kstech.exccheck.R;
import com.kstech.exccheck.config.ConfigFileManager;
import com.kstech.exccheck.creatxml.view.EditActivity;
import com.kstech.exccheck.db.UserDao;
import com.kstech.exccheck.domain.checkline.CheckLineLoadTask;
import com.kstech.exccheck.domain.user.User;
import com.kstech.exccheck.domain.user.UserStatusEnum;
import com.kstech.exccheck.util.AppContext;
import com.kstech.exccheck.util.MD5Utils;
import com.kstech.exccheck.util.SystemUtil;
import com.kstech.exccheck.view.check.AdminIndexActivity;
import com.kstech.exccheck.view.user.LoginUserListAdspter;

/**
 * 登录主界面
 * @author lijie
 */
public class MainActivity extends BaseActivity {

    // 用户名
    private TextView userNameET, checkLineET;
    private EditText passwordET;
    // 密码
    private Button loginBtn;
    private LinearLayout userNameLy, checkLineLy;

    private ImageView ivToEdit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 初始化视图组件
        initView();
        // 如果不是首次登录，则默认显示上一次登录的用户
        String lastUserName = ConfigFileManager.getInstance().getLastUserName();
        if (lastUserName == null || lastUserName.length() == 0) {
            userNameET.setText(UserDao.getAdminName());
        } else {
            userNameET.setText(lastUserName);
        }

        AppContext.initResource();
        // 默认显示上一次检线的名称
        checkLineET.setText(AppContext.getCurrentCheckLine().getName());

        // 点击任何位置收键盘
        SystemUtil.setHideSoftKeyBoardListener(MainActivity.this,
                R.id.activityMain);
        if(checkWIFIisOpen()){
            //检查平板是否已被授权
            checkPriority();
        }else {
            startActivity(new Intent(MainActivity.this,CheckIndexActivity.class));
            finish();
        }


    }

    private boolean checkWIFIisOpen() {
        WifiManager localWifiManager = (WifiManager) AppContext.context
                .getSystemService(Context.WIFI_SERVICE);
        if(localWifiManager.getWifiState()==1){
            Log.i("WifiState", "wifi not open");
            return false;
        }else {return true;}
        // 0正在关闭,1WIFi不可用,2正在打开,3可用,4状态不可zhi
    }

    /*
     * 初始化视图组件
     */
    private void initView() {
        // 用户名组件
        userNameET = (TextView) findViewById(R.id.userNameET);
        // 密码组件
        passwordET = (EditText) findViewById(R.id.passwordET);
        // 检线
        checkLineET = (TextView) findViewById(R.id.checkLineET);
        // 登录按钮组件
        loginBtn = (Button) findViewById(R.id.loginBtn);
        loginBtn.setOnClickListener(loginBtnListener);
        // 整个用户名的layout框
        userNameLy = (LinearLayout) findViewById(R.id.userNameLy);
        userNameLy.setOnClickListener(userNameETListener);
        checkLineLy = (LinearLayout) findViewById(R.id.checkLineLy);
        checkLineLy.setOnClickListener(checkLineETListener);
        ivToEdit = (ImageView) findViewById(R.id.iv_to_xml_edit);
        ivToEdit.setOnClickListener(new View.OnClickListener() {
            long[] mHints = new long[4];//初始全部为0
            @Override
            public void onClick(View view) {
                //将mHints数组内的所有元素左移一个位置
                System.arraycopy(mHints, 1, mHints, 0, mHints.length - 1);
                //获得当前系统已经启动的时间
                mHints[mHints.length - 1] = SystemClock.uptimeMillis();
                if (SystemClock.uptimeMillis()-mHints[0]<=1000) {
                    startActivity(new Intent(MainActivity.this, IndexActivity.class));
                    finish();
                }
            }
        });
    }

    /**
     * The User name et listener.
     */
/*
     * 用户名监听
     */
    View.OnClickListener userNameETListener = new View.OnClickListener() {
        public void onClick(View arg0) {
            SystemUtil.hideSoftKeyBoard(MainActivity.this);

            // 展示用户选择dialog
            LayoutInflater inflater = (LayoutInflater) AppContext.context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View login_user_view = inflater.inflate(R.layout.login_user_view,
                    null);
            ListView loginUserList = (ListView) login_user_view
                    .findViewById(R.id.loginUserView);
            final List<Map<String, Object>> result = UserDao
                    .findUserListReturnListMap(UserStatusEnum.ENABLE.getCode());
            LoginUserListAdspter adapter = new LoginUserListAdspter(
                    AppContext.context, result);
            loginUserList.setAdapter(adapter);

            AlertDialog.Builder builder = new AlertDialog.Builder(
                    AppContext.context);
            builder.setView(login_user_view);
            final AlertDialog dialog = builder.create();
            dialog.show();
            dialog.getWindow().setLayout(800, 600);
            // end

            loginUserList.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1,
                                        int arg2, long arg3) {
                    // 显示选择的用户名称
                    userNameET.setText(result.get(arg2).get("name").toString());
                    dialog.cancel();
                }
            });
        }
    };

    /**
     * The Check line et listener.
     */
/*
     * 检线监听
     */
    View.OnClickListener checkLineETListener = new View.OnClickListener() {
        public void onClick(View arg0) {
            SystemUtil.hideSoftKeyBoard(MainActivity.this);
            // 获取检线
            CheckLineLoadTask loadTask = new CheckLineLoadTask(checkLineET);
            loadTask.execute(100);
        }
    };

    /**
     * The Login btn listener.
     */
/*
     * 点击登录按钮
     */
    Button.OnClickListener loginBtnListener = new Button.OnClickListener() {
        public void onClick(View arg0) {
            String userName = userNameET.getText().toString();
            String pwd = passwordET.getText().toString();

            // 校验页面必填项信息
            if ("".equals(pwd)) {
                new AlertDialog.Builder(MainActivity.this)
                        .setMessage(R.string.passwordEmpty)
                        .setNeutralButton(R.string.str_ok, null).show();
                return;
            }

            User currentUser = UserDao.login(userName, pwd);
            if (currentUser == null) {// 说明登录失败
                // 错误提示
                new AlertDialog.Builder(MainActivity.this)
                        .setMessage(R.string.passwordError)
                        .setNeutralButton(R.string.str_ok, null).show();
            } else {
                ConfigFileManager.getInstance().saveCheckLineName(AppContext.getCurrentCheckLine().getName());
                ConfigFileManager.getInstance().saveCheckLineSsid(AppContext.getCurrentCheckLine().getSsid());
                // 跳转到管理员首页
                Intent adminIntent = new Intent(MainActivity.this,
                        AdminIndexActivity.class);
                startActivity(adminIntent);
                finish();
            }
        }
    };

    private void checkPriority(){
        String s = MD5Utils.getMac();
        s = MD5Utils.md5(s);
        String rs = MD5Utils.readMD5file();
        if(!s.equals(rs)){
            MD5Utils.UninstallAPP(this);
            finish();
        }
    }
}
